#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import pymysql

def get_connection_cursor():
    connection = pymysql.connect(host='localhost', user='root', passwd='root', db='dashuju', charset='utf8')
    return connection, connection.cursor()

def execute_insert_update_delete(sql, cursor):
    return cursor.execute(sql)

def execute_query(sql, cursor):
    cursor.execute(sql)
    return  cursor.fetchall()

def commit_(connection):
    if connection:
        connection.commit()

def rollback_(connection):
    if connection:
        connection.rollback()

def close_(connection, cursor):
    if cursor:
        cursor.close()
    if connection:
        connection.close()

def execute_(sql):
    connection, cursor, result = None, None, None
    try:
        connection, cursor = get_connection_cursor()
        if str(sql).lower().startswith("select"):
            result = execute_query(sql, cursor)
        else:
            result = execute_insert_update_delete(sql, cursor)
            commit_(connection)
    except Exception as e:
        print(e)
        rollback_(connection)
    finally:
        close_(connection, cursor)

    return result